package com.bang.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @ClassName: FutureExample
 * @Desc: 实现Callable接口, 重写call方法, 线程池执行submit时,返回Future,调用future会阻塞线程
 * @auther: BANG
 * @Date: 2019/10/09 09:16
 * @Version: 1.0
 * @Modified By:
 */
@Slf4j
public class FutureExample {


    static class MyCallable implements Callable<String> {

        /**
         * Computes a result, or throws an exception if unable to do so.
         *
         * @return computed result
         * @throws Exception if unable to compute a result
         */
        @Override
        public String call() throws Exception {
            Thread.sleep(5000);
            log.error("The MyCallable is running");
            return "down";
        }

    }

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        try {
            Future<String> future = executorService.submit(new MyCallable());
            log.error("Main线程开始执行-----------");
//        String res = future.get();
            String res = future.get(1, TimeUnit.SECONDS);
            log.error("res {}", res);
            log.error("Main线程开始执行-----------");

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }

    }
}
